import axios from "axios";
import store from "@/store"
import { Toast } from 'vant'
import router from '@/router'
const baseURL = 'http://localhost:8080'

const v = '/api'

const instance = axios.create({
    baseURL: baseURL + v,
    timeout: 5000,
    headers: {}
})

instance.interceptors.request.use(function (config) {
    // 添加token(鉴权信息在header)
    config.headers.Authorization = store.state.user.token
    return config
}, function (error) {
    return Promise.reject(error)
})

instance.interceptors.response.use(function (response) {
    if (response.status === 200) {
        if (response.data && response.data.err === 0) {
            return response.data.data
        } else if (response.data.err === -1) {
            store.commit('user/updateToken', null)
            localStorage.removeItem('token')
            router.replace('/login')
        }
        else {
            return response.data
        }
    } else {
        Toast.fail('网络异常')
    }
    return response
}, function (error) {
    Toast.fail('网络异常')
    return Promise.reject(error)
})

export default instance